package com.cyy.friend.service;

import com.cyy.friend.client.UserClient;
import com.cyy.friend.dao.FriendDao;
import com.cyy.friend.dao.NoFriendDao;
import com.cyy.friend.pojo.Friend;
import com.cyy.friend.pojo.NoFriend;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@Service
public class FriendService {

    @Autowired
    private FriendDao friendDao;

    @Autowired
    private NoFriendDao noFriendDao;

    @Autowired
    private UserClient userClient;

    public void addNoFriend(String userid,String friendid){

        NoFriend noFriend = new NoFriend();
        noFriend.setFriendid(friendid);
        noFriend.setUserid(userid);
        noFriendDao.save(noFriend);
    }

    /**
     * 添加朋友
     */
    @Transactional
    public int addFriend(String userid,String friendid){

        //判断用户是否添加过该朋友，如果有则返回0
        if(friendDao.selectCount(userid,friendid) > 0){
            return 0;
        }
        Friend friend = new Friend();
        friend.setFriendid(friendid);
        friend.setUserid(userid);
        friend.setIslike("0");
        friendDao.save(friend);

        //判断对方是否也喜欢你
        if(friendDao.selectCount(friendid,userid) > 0){
            friendDao.updateLike(friendid,userid,"1");
            friendDao.updateLike(userid,friendid,"1");
        }

        userClient.incFansCount(friendid,1);
        userClient.incFollowCount(userid,1);
        return 1;
    }

    /**
     * 删除喜欢
     */
    @Transactional
    public void deleteFriend(String userid,String friendid){
        friendDao.deleteFriend(userid,friendid);
        friendDao.updateLike(friendid,userid,"0");
        //减少关注数和对方的粉丝数
        userClient.incFollowCount(userid,-1);
        userClient.incFansCount(friendid,-1);
        addNoFriend(userid,friendid); //向不喜欢中添加记录
    }

}
